<?php

namespace app\admin\controller\task;

use app\admin\model\TaskJob;
use app\admin\model\Gateway;
use app\admin\model\Sound;
use app\admin\model\TaskGatewayAccess;
use app\admin\model\TaskAdminAccess;
use app\admin\model\Blacklist;

use app\admin\model\Saler;
use app\admin\model\SalerGroup;
use app\admin\model\SalerGroupInfo;

use app\common\controller\Backend;

use app\common\library\FSHelper;
use think\Db;

/**
 * 呼叫任务管理
 *
 * @icon fa fa-circle-o
 */
class Task extends Backend
{

    /**
     * Task模型对象
     */
    protected $model = null;

    protected $childrenAdminIds = [];

    protected $fsHelper = null;

    protected $dataLimit = 'auth';

    protected $multiFields = '';

    protected $searchFields = 'name';

    protected $noNeedRight = ['pause'];

    public function _initialize()
    {
        parent::_initialize();

        $this->model = model('Task');
        $this->view->assign("callbackTypeList", $this->model->getCallbackTypeList());
        $this->view->assign("stateList", $this->model->getStateList());
    }

    protected function getChildrenGatewayIds($withself = false)
    {
        $gatewayIds = [];
        $adminIds = $this->auth->getChildrenAdminIds($withself);
        $gatewayList = collection(Gateway::field('id')->where('admin_id', 'in', $adminIds)->select())->toArray();
        foreach ($gatewayList as $k => $v) {
            $gatewayIds[] = $v['id'];
        }
        return $gatewayIds;
    }

    protected function getChildrenSoundIds($withself = false)
    {
        $soundIds = [];
        $adminIds = $this->auth->getChildrenAdminIds($withself);
        $soundList = collection(Sound::field('id, type')->where('admin_id', 'in', $adminIds)->select())->toArray();
        foreach ($soundList as $k => $v) {
            $soundIds[] = $v['id'];
        }
        return $soundIds;
    }




    /**
     * 查看
     */
    public function index()
    {

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with('admin,speech')
                // ->with('sound')
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with('admin,speech')
                //->with('sound')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
//            $openId = Db::name('admin')->where('id',$this->auth->id)->field('openid')->find();
//
//            $openId = $openId['openid']?1:0;

            foreach ($list as $key=>$row) {
                $row->getRelation('admin')->visible(['nickname']);
                $row->getRelation('speech')->visible(['name']);
//                $row->sub_status = $openId;
                $row->wx_url = '/admin/qrcode/index?taskId='.$row['id'];
                //todo 这样写不合理，重构的时候清理
                $taskSub = Db::name('task_wx')->where('tid',$row['id'])->find();
                $row->task_sub = $taskSub?1:0;
                $row->sub_status = $taskSub?1:0;

                $gateway_id=Db::name('task_gateway_access')->where(['tid'=>$row['id']])->field('gateway_id')->select();
                $gateway_list=Db::name('gateway')->where('id','in',array_column($gateway_id, 'gateway_id'))->field('name')->select();
                $list[$key]['gateway_name']=implode(',',array_column($gateway_list, 'name'));
            }

            $list = collection($list)->toArray();
            /******************数据不对称start*********/
             foreach($list as $key=>$value){
                 $count_all = Db::name('TaskJob')->alias('a')
                     ->where(['tid'=>$value['id']])
                     ->count();
                 $count_none = Db::name('TaskJob')->alias('a')
                          ->where(['tid'=>$value['id'],'callstate'=>'none'])
                          ->count();
                 $count_succ = Db::name('TaskJob')->alias('a')
                     ->where(['tid'=>$value['id'],'callstate'=>'success'])
                     ->count();
                 $count_fail = Db::name('TaskJob')->alias('a')
                     ->where(['tid'=>$value['id'],'callstate'=>'fail'])
                     ->count();
                 $list[$key]['fail_count'] =$count_fail;
                 $list[$key]['success_count'] = $count_succ;
                 $list[$key]['total_count'] =  $count_all;
                 $list[$key]['done_count'] = $count_fail+$count_succ;


             }
            /******************数据不对称end*********/
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * @param $taskId
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 关注任务
     */
    public function tasksub($taskId)
    {
        //检验是否存在openid
//        $check = Db::name('admin')->where('id',$this->auth->id)->field('openid')->find();
//        if(!$check['openid']){
//            return ['code'=>3,'msg'=>'请先关注订阅号'];
//        }

        if($taskId){
            $result = Db::name('task_wx')
                ->where('tid',$taskId)
                ->find();

            if(!$result){
                return ['code'=>1,'msg'=>'您尚未订阅'];
            }
            return ['code'=>200,'msg'=>'订阅成功'];
        }
        return ['code'=>2,'msg'=>'参数错误'];
    }


    /**
     * 解除消息推送订阅
     */
    public function unsubtask($taskId)
    {
        $check = Db::name('admin')->where('id',$this->auth->id)->field('openid')->find();
        if(!$check){
            return ['code'=> 1001,'msg'=> '系统错误'];
        }
        if(!$taskId){
            return ['code'=> 1002,'msg'=> '参数错误'];
        }

        $taskInfo = Db::name('task_wx')
            ->where('tid',$taskId)
            ->find();
        if(!$taskInfo){
            return ['code'=>1004,'msg'=>'您尚未订阅该任务'];
        }

        Db::name('task_wx')
            ->where('tid',$taskId)
            ->delete();
        return ['code'=>200,'msg'=>'操作成功'];

    }


    protected function importTaskJobs($tid, $filePath, &$import_count)
    {
        $filePath = ROOT_PATH . '/public' . $filePath;
        if (!is_file($filePath)) {
            //$this->error(__('No results were found'));
            return __('No results were found');
        }
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                $PHPReader = new \PHPExcel_Reader_CSV();
                if (!$PHPReader->canRead($filePath)) {
                    //$this->error(__('Unknown data format'));
                    return __('Unknown data format');
                }
            }
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $PHPExcel = $PHPReader->load($filePath); //加载文件
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);
        for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $fields[$currentColumn] = $val;
            }
        }
        $template_fields = array('呼叫号码', '客户名称');
        $fields = array_intersect($fields, $template_fields);
        if (count($fields) < count($template_fields)) {
            //$this->error(__('导入的表格字段有误，<br />必须含有 [呼叫号码] 和 [客户名称] 两列'));
            return __('导入的表格格式有误，<br />必须含有 [呼叫号码] 和 [客户名称] 两列');
        }
        $insert = [];
        $numbers_added = [];
        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            $values = [];
            //for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++)
            foreach ($fields as $k => $v) {
                $val = $currentSheet->getCellByColumnAndRow($k, $currentRow)->getValue();
                $values[] = is_null($val) ? '' : $val;
            }
            $row = [];
            $temp = array_combine($fields, $values);
            $number = trim($temp['呼叫号码']);
            if (array_key_exists($number, $numbers_added)) {
                continue;
            }
            $numbers_added[$number] = 1;
            $number_length = strlen($number);
            if (!in_array($number_length, array(8, 11, 12))) {
                continue;
            }
            $blacklist = Blacklist::where('number', '=', $number)->find();
            if (!empty($blacklist)) {
                continue;
            }
            $row['number'] = $number;
            $row['name'] = $temp['客户名称'];
            $row['admin_id'] = $this->auth->id;
            $row['tid'] = $tid;

            if ($row) {
                $insert[] = $row;
            }
        }
        if (!$insert) {
            //$this->error(__('No rows were updated'));
            return __('No rows were updated');
        }
        try {
            if (count($insert) > 3000) {
                return __('测试环境最多支持导入3000个号码<br/>以免由于操作失误导致浪费话费！');
            }
            $model = model('TaskJob');
            $result = $model->saveAll($insert);
            $import_count = 0;
            foreach ($result as $one) {
                if (is_object($one)) {
                    $import_count++;
                }
            }
        } catch (\think\exception\PDOException $exception) {
            //$this->error($exception->getMessage());
            return __($exception->getMessage());
        }
    }

    protected function importTaskJobs_From_Group($tid, $group_id, &$import_count)
    {

        $insert = [];
        $numbers_added = [];

        $groupInfoList = SalerGroupInfo::where('saler_group_id', '=', $group_id)->select();

        foreach ($groupInfoList as $one) {
            $row = [];
            $saler = Saler::where('id', '=', $one->saler_id)->find();
            if (empty($saler)) {
                continue;
            }
            $row['number'] = $saler->tel;
            $row['name'] = $saler->name;
            $row['admin_id'] = $this->auth->id;
            $row['tid'] = $tid;
            if ($row) {
                $insert[] = $row;
            }
        }

        if (!$insert) {
            //$this->error(__('No rows were updated'));
            return __('No call group number');
        }
        try {
            if (count($insert) > 3000) {
                return __('测试环境最多支持导入3000个号码<br/>以免由于操作失误导致浪费话费！');
            }
            $model = model('TaskJob');
            $result = $model->saveAll($insert);

            $import_count = 0;
            foreach ($result as $one) {
                if (is_object($one)) {
                    $import_count++;
                }
            }
        } catch (\think\exception\PDOException $exception) {
            //$this->error($exception->getMessage());
            return __($exception->getMessage());
        }
    }


    public function getChinese($string,$encode="UTF-8") {
        switch($encode){
            case "GBK" :$codelength=2;break;
            case "GB2312" :$codelength=3;break;
            case "UTF-8" :$codelength=3;break;
            case "UTF-16" :$codelength=4;break;
        }
        $tmpstr = '';
        $arr = array(1,2,3,4,5,6,7,8,9,0);
        $strlen = strlen($string);
        for($i=0; $i<$strlen; $i++) {
            $str=substr($string, $i, 1);
            $str1=trim($str);
            if( ord($str)>0xA0 ){
                $tmpstr.= substr($string, $i, $codelength);
                $i = $i+$codelength-1;
            }
        }
        return $tmpstr;
    }

    public function add()
    {

        /*
        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        $gatewayList = collection(Gateway::where('admin_id', 'in', $this->childrenAdminIds)->select())->toArray();
        $gatewaydata = [];
        foreach ($gatewayList as $k => $v) {
            $gatewaydata[$v['id']] = $v['name'];
        }
        $call
        $this->view->assign('gatewaydata', $gatewaydata);
        */

        if (!$this->auth->isSuperAdmin) {
            $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
            $childrenGatewayIds = $this->getChildrenGatewayIds(true);

            $gateway_ids = implode(',', $childrenGatewayIds);
            $this->view->assign('gateway_ids', $gateway_ids);
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }

                    $pathTts = Db::name('sound')
                        ->alias('s')
                        ->join('speech_router r','s.id = r.sound_id or s.id =r.no_sound_id','left')
                        ->where('r.speech_id',$params['speech_id'])
                        ->where('s.tts','<>',-1)
                        ->field('r.id,r.sound_id,r.no_sound_id,s.id as ids,s.tts,s.content')
                        ->select();

//                    $keywordTts = Db::name('sound')
//                        ->alias('s')
//                        ->join('speech_faq f','s.id = f.sound_id or s.id =f.no_sound_id','left')
//                        ->where('f.speech_id',$params['speech_id'])
//                        ->where('s.tts','<>',-1)
//                        ->field('f.id as faq_id,f.sound_id,f.no_sound_id,s.id as ids,s.tts,s.content')
//                        ->select();
//                    $ttsCheck = array_merge($pathTts,$keywordTts);
                    $ttsCheck = $pathTts;

                    $ttsFormat  = '';
                    $tts        =  [];
                    $lock       = 0;
                    if($ttsCheck)
                    {
                        //将同一个router的信息重组
                        foreach ($ttsCheck as $value)
                        {
                            if($value['tts'])
                            {
                                $lock =1;
                                preg_match_all('#[A-Za-z]{1,}#',$value['content'],$regular);
                                $regularCount = count($regular[0]);
                                if($regularCount==1 && isset($regular[0][0]) &&$regular[0][0] =='name')
                                {
                                    $lock =2;
                                }
                            }
                            if($value['tts'] != -1){

                                $column = strtolower($value['content']);
                                $column = trim($column);
                                $column = str_replace(' ', '', $column);

                                if(isset($value['id']))
                                {
                                    $tts[$value['id']]['router_id']    = $value['id'];
                                    $tts[$value['id']]['faq_id']       = '';
                                    $tts[$value['id']]['sound_id']     = $value['sound_id'];
                                    $tts[$value['id']]['no_sound_id']  = $value['no_sound_id'];
                                    $tts[$value['id']]['tts']          = $value['tts'];

                                    if($value['sound_id']==$value['ids'])
                                    {
                                        $tts[$value['id']]['content'] = $column;
                                    }

                                    if($value['no_sound_id']==$value['ids'])
                                    {
                                        $tts[$value['id']]['no_content'] = $column;
                                    }
                                }
//                                if(isset($value['faq_id']))
//                                {
//                                    $tts[$value['faq_id']]['faq_id']       = $value['faq_id'];
//                                    $tts[$value['faq_id']]['router_id']    = '';
//                                    $tts[$value['faq_id']]['sound_id']     = $value['sound_id'];
//                                    $tts[$value['faq_id']]['no_sound_id']  = $value['no_sound_id'];
//                                    $tts[$value['faq_id']]['tts']          = $value['tts'];
//
//                                    if($value['sound_id']==$value['ids'])
//                                    {
//                                        $tts[$value['faq_id']]['content'] = $column;
//                                    }
//
//                                    if($value['no_sound_id']==$value['ids'])
//                                    {
//                                        $tts[$value['faq_id']]['no_content'] = $column;
//                                    }
//                                }

                            }


                        }


                        if($tts && $lock)
                        {

                            $ttsInfo = Db::name('saler_group_info')
                                ->alias('i')
                                ->join('saler s','s.id = i.saler_id')
                                ->where('i.saler_group_id',$params['saler_group_id'])
                                ->field('s.id,name,s.tts_format')
                                ->select();

                            if($lock &&(!$ttsInfo || !$ttsInfo[0]['tts_format']))
                            {
                               $this->error('您选择的客户群组没有匹配的字段');
                            }

                            $ttsColumn = json_decode($ttsInfo[0]['tts_format']);
                            $ttsArr = array_keys((array)$ttsColumn);
                            array_push($ttsArr,'name');

                            $check1 =$check2 = [];
                            foreach ($tts as $val1)
                            {
                                preg_match_all('#[A-Za-z]{1,}#',$val1['content'],$arr);
                                $check1[] = $arr[0];

                                if(isset($val1['no_content']))
                                {
                                    preg_match_all('#[A-Za-z]{1,}#',$val1['no_content'],$arrNo);
                                    $check2[] = $arrNo[0];

                                }

                            }


                            foreach ($check1 as $value)
                            {
                                foreach ($value as $val)
                                {
                                    if(!in_array($val,$ttsArr))
                                    {
                                        $this->error('您合成的引导语音与客户群组的列名不一致');
                                    }
                                }

                            }

                            foreach ($check2 as $value)
                            {
                                foreach ($value as $val)
                                {
                                    if(!in_array($val,$ttsArr))
                                    {
                                        $this->error('您合成的挽回语音与客户群组的列名不一致');
                                    }
                                }

                            }

                            $ttsFormat = $ttsInfo;

                        }

                    }


                    /*
                    if (!is_file(ROOT_PATH . '/public' . $params['task_file'])) {
                        $this->error(__('任务文件 \'%s\' 不存在', $params['task_file']));
                    }
                    if (in_array($params['callback_type'], array('transfer', 'ivr_transfer')) && empty($params['admin_ids'])) {
                        $this->error(__('请选择回叫分机！'));
                    }
                    */
                    $group = SalerGroup::where('id', '=', $params['saler_group_id'])->find();
                    if (empty($group)) {
                        $this->error(__('客户群组不存在！'));
                    }
                    $params['saler_group_name'] = $group['name'];

                    $params['progress'] = '0%';
                    $params['total_count'] = 0;
                    $params['done_count'] = 0;
                    $params['success_count'] = 0;
                    $params['fail_count'] = 0;
                    $params['status'] = '';
                    $params['state'] = 2;

                    $result = $this->model->allowField(true)->save($params);

                    if ($result == false) {
                        $this->error('系统错误');
                    }

                    $import_count = 0;
                    $import_error = $this->importTaskJobs_From_Group($this->model->id, $params['saler_group_id'], $import_count);

                    if($ttsFormat)
                    {
                        //匹配tts字符串中是否含有name，没有的话用表中字段name赋值
                        $nameLock1 = $nameLock2 ='';
                        foreach ($tts as $value)
                        {
                            if(strpos($value['content'],'name'))
                            {
                                $nameLock1 =1;
                            }
                            if (isset($value['no_content']))
                            {
                                if(strpos($value['no_content'],'name'))
                                {
                                    $nameLock2 =1;
                                }
                            }
                        }

                        foreach ($ttsFormat as $value){
                            $data = (array)json_decode($value['tts_format']);
                            foreach ($tts as $val)
                            {
                                $str = $val['content'];
                                $noStr = isset($val['no_content'])?$val['no_content']:'';

                                foreach ($data as $k => $v)
                                {
                                    $str = str_replace('#'.$k.'#',$v,$str);
                                    $noStr = str_replace('#'.$k.'#',$v,$noStr);
                                }

                                if($nameLock1)
                                {
                                    $str = str_replace('name',$value['name'],$str);
                                }
                                if($nameLock2)
                                {
                                    $noStr = str_replace('name',$value['name'],$noStr);
                                }

                                $jobId = Db::name('task_job')
                                    ->alias('j')
                                    ->join('saler s','s.tel = j.number')
                                    ->where('s.id',$value['id'])
                                    ->where('j.tid',$this->model->id)
                                    ->value('j.id');

                                Db::name('speech_tts')
                                    ->insert([
                                        'admin_id'       => $this->auth->id,
                                        'saler_group_id' => $params['saler_group_id'],
                                        'saler_id'       => $value['id'],
                                        'speech_id'      => $params['speech_id'],
                                        'router_id'      => isset($val['router_id'])?$val['router_id']:'',
                                        'faq_id'         => isset($val['faq_id'])?$val['faq_id']:'',
                                        'content'        => $str,
                                        'no_content'     => $noStr,
                                        'sount_content'  => $val['content'],
                                        'no_sound_content'  => isset($val['no_content'])?$val['no_content']:'',
                                        'sound_id'       => $val['sound_id'],
                                        'no_sound_id'    => $val['no_sound_id'],
                                        'task_id'        => $this->model->id,
                                        'job_id'         => $jobId,
                                        'created_at'     => date('Y-m-d H:i:s')
                                ]);
                            }


                        }

                    }
                    
                    $this->model->save(array('total_count' => $import_count));

                    if (!empty($import_error)) {
                        $this->model->delete();
                        $this->error($import_error);
                    }

                    $gateway = explode(',', $params['gateway_ids']);
                    if (!$this->auth->isSuperAdmin) {
                        //过滤不允许的组别,避免越权
                        $gateway = array_intersect($childrenGatewayIds, $gateway);
                    }
                    $dataset = [];
                    foreach ($gateway as $value) {
                        $dataset[] = ['tid' => $this->model->id, 'gateway_id' => $value];
                    }
                    model('TaskGatewayAccess')->saveAll($dataset);

                    /*
		    $admin = explode(',', $params['admin_ids']);
                    if (! $this->auth->isSuperAdmin) {
		                //过滤不允许的组别,避免越权
                        $admin = array_intersect($this->childrenAdminIds, $admin);
                    }
                    $dataset = [];
                    foreach ($admin as $value)
                    {
                        $dataset[] = ['tid' => $this->model->id, 'admin_id' => $value];
                    }
                    model('TaskAdminAccess')->saveAll($dataset);
                    */

                    $this->success();
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();

    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        $gateway_ids = [];
        $gatewayList = collection(TaskGatewayAccess::field('gateway_id')->where('tid', '=', $row['id'])->select())->toArray();
        foreach ($gatewayList as $k => $v) {
            $gateway_ids[] = $v['gateway_id'];
        }
        $row['gateway_ids'] = implode(',', $gateway_ids);
        unset($gateway_ids);
        unset($gatewayList);

        /*$admin_ids = [];
        $adminList = collection(TaskAdminAccess::field('admin_id')->where('tid', '=', $row['id'])->select())->toArray();
        foreach ($adminList as $k => $v) {
            $admin_ids[] = $v['admin_id'];
        }
        $row['admin_ids'] = implode(',',$admin_ids);
        unset($admin_ids);
        unset($adminList);*/

        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            if (!$this->auth->isSuperAdmin) {
                $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
                $childrenGatewayIds = $this->getChildrenGatewayIds(true);
            }
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    /*
                    if (!is_file(ROOT_PATH . '/public' . $params['task_file'])) {
                        $this->error(__('任务文件 \'%s\' 不存在', $params['task_file']));
                    }
                    if (in_array($params['callback_type'], array('transfer', 'ivr_transfer')) && empty($params['admin_ids'])) {
                        $this->error(__('请选择回叫分机！'));
                    }
                    */
                    unset($params['admin_id']);
                    unset($params['task_file']);
                    unset($params['progress']);
                    unset($params['total_count']);
                    unset($params['done_count']);
                    unset($params['success_count']);
                    unset($params['fail_count']);
                    unset($params['status']);
                    unset($params['state']);
                    $result = $row->allowField(true)->save($params);
                    if ($result == false) {
                        $this->error($this->model->getError());
                    }
                    // 先移除所有权限
                    model('TaskGatewayAccess')->where('tid', $row->id)->delete();
                    $gateway = explode(',', $params['gateway_ids']);

                    if (!$this->auth->isSuperAdmin) {
                        //过滤不允许的组别,避免越权
                        $gateway = array_intersect($childrenGatewayIds, $gateway);
                    }
                    $dataset = [];
                    foreach ($gateway as $value) {
                        $dataset[] = ['tid' => $row->id, 'gateway_id' => $value];
                    }
                    model('TaskGatewayAccess')->saveAll($dataset);

                    // 先移除所有权限
                    /*model('TaskAdminAccess')->where('tid', $row->id)->delete();
                            $admin = explode(',', $params['admin_ids']);
                            if (! $this->auth->isSuperAdmin) {
                                //过滤不允许的组别,避免越权
                                $admin = array_intersect($this->childrenAdminIds, $admin);
                            }
                            $dataset = [];
                            foreach ($admin as $value)
                            {
                                $dataset[] = ['tid' => $row->id, 'admin_id' => $value];
                            }
                            model('TaskAdminAccess')->saveAll($dataset);
                            */

                    $this->success();
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            $count = 0;
            if (is_array($adminIds)) {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            ///usr/share/nginx/www            $count = 0;
            foreach ($list as $k => $v) {
                //$count += $v->delete();
                if ($v->delete()) {
                    TaskJob::where('tid', '=', $v->id)->delete();
                    model('TaskGatewayAccess')->where('tid', $v->id)->delete();
                    //model('TaskAdminAccess')->where('tid', $v->id)->delete();
                    $count++;
                }
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    protected function clearTaskProgress($taskId, $onlyFailed = false)
    {
        $task = \app\admin\model\Task::where('id', '=', $taskId)->find();
        if (empty($task)) {
            return;
        }
        $update_sql = 'update fa_task_job set called=?, calltime=?, callgateway=?, callstate=?, failreason=?, ivrstate=?, queuestate=?, receptionextension=?, record_path=?, updatetime=? where tid=?';
        if ($onlyFailed) {
            if ($task->callback_type == 'ivr') {
                $update_sql = $update_sql . ' and called = 1 and ivrstate in (\'none\')';
            } else {
                $update_sql = $update_sql . ' and called = 1 and queuestate in (\'none\', \'queued\')';
            }
        }
        $result = Db()->execute($update_sql, [0, 0, '', 'none', '', 'none', 'none', '', '', time(), $task->id]);
        $task->fail_count = 0;
        $task->save();
    }

    /**
     * 开始任务
     */
    public function start($ids = NULL)
    {

        if (!$this->request->isPost()) {
            $this->error(__('You have no permission'));
        }

        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        if ($row['state'] == 1) {
            $this->error(__('该任务已开始'));
        }
        if ($row['state'] == 2) {
            //TODO: 清除该任务进度
            $this->clearTaskProgress($row['id']);
        }

        $this->fsHelper = new FSHelper();
        $this->fsHelper->prepareCallbackForTask($row['id']);

        $params = array();
        $params['state'] = 1;
        $params['manual_status']=0;
        $result = $row->save($params);

        if ($result == false) {
            $this->error($this->model->getError());
        }

        $this->success();

    }

    /**
     * 重试任务
     */
    public function retry($ids = NULL)
    {

        if (!$this->request->isPost()) {
            $this->error(__('You have no permission'));
        }

        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($row['state'] == 0) {
            $this->error(__('该任务已暂停'));
        }
        if ($row['state'] == 1) {
            $this->error(__('该任务已开始'));
        }
        if ($row['state'] == 2) {
            //TODO: 清除该任务进度
            $this->clearTaskProgress($row['id'], true);
        }

        $this->fsHelper = new FSHelper();
        $this->fsHelper->prepareCallbackForTask($row['id']);

        $params = array();
        $params['state'] = 1;
        $result = $row->save($params);

        if ($result == false) {
            $this->error($this->model->getError());
        }

        $this->success();

    }

    /**
     * 停止任务
     */
    public function stop($ids = NULL)
    {

        if (!$this->request->isPost()) {
            $this->error(__('You have no permission'));
        }

        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        if ($row['state'] == 2) {
            $this->error(__('该任务已停止'));
        }
        $params = array();
        $params['state'] = 2;
        $result = $row->save($params);

        if ($result == false) {
            $this->error($this->model->getError());
        }

        $this->fsHelper = new FSHelper();
        $this->fsHelper->removeCallbackForTask($row['id']);

        $this->success();

    }

    /**
     * 停止任务
     */
    public function pause($ids = NULL)
    {

        if (!$this->request->isPost()) {
            $this->error(__('You have no permission'));
        }

        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        if ($row['state'] == 0) {
            $this->error(__('该任务已暂停'));
        }
        $params = array();
        $params['state'] = 0;
        $params['manual_status'] =1;
        $result = $row->save($params);

        if ($result == false) {
            $this->error($this->model->getError());
        }

        $this->fsHelper = new FSHelper();
        $this->fsHelper->removeCallbackForTask($row['id']);

        $this->success();

    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


}
